package cn.chench.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import cn.chench.util.LoggerUtil;
import reactor.core.publisher.Mono;

@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {

	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		// 请求对象
		ServerHttpRequest request = exchange.getRequest();
		// 响应对象
		ServerHttpResponse response = exchange.getResponse();
		// 获取请求地址
		String beforePath = request.getPath().pathWithinApplication().value();
		// 获取响应状态码
		HttpStatus beforeStatusCode = response.getStatusCode();
		LoggerUtil.info("请求前 -> before -> 响应码：" + beforeStatusCode + "，请求路径：" + beforePath);
		//exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
		//return exchange.getResponse().setComplete();
		return chain.filter(exchange).then(Mono.fromRunnable(() -> {
			// 获取请求地址
			String afterPath = request.getPath().pathWithinApplication().value();
			// 获取响应状态码
			HttpStatus afterStatusCode = response.getStatusCode();
			LoggerUtil.info("响应后 -> after -> 响应码：" + afterStatusCode + "，请求路径：" + afterPath);
		}));
	}

	public int getOrder() {
		return 0;
	}
}
